﻿
#region Imports...
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Pharmacy.Web.UI;
using Pharmacy.Settings.BusinessLayer;
using Pharmacy.Data;
using Pharmacy.Entities;
using System.Web.Services;
using Telerik.Web.UI;

#endregion

public partial class ExportAdjustEdit : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        FormUtil.RedirectAfterInsertUpdate(FormView1, "ExportAdjustEdit.aspx?{0}", StockOutDataSource);
        FormUtil.RedirectAfterCancel(FormView1, "ExportAdjust.aspx");
        FormUtil.SetDefaultMode(FormView1, "StockOutId");

    }
    protected void FormView1_Load(object sender, EventArgs e)
    {
        DropDownList dataPreparedBy = (DropDownList)FormView1.Row.FindControl("dataPreparedBy");
        dataPreparedBy.SelectedValue = Request.Cookies["LoginUser"].Value;
        dataPreparedBy.Enabled = false;
        if (FormView1.CurrentMode == FormViewMode.Insert)
        {
            TextBox tbStockOutId = (TextBox)FormView1.Row.FindControl("dataStockOutID");
            TextBox tbStockOutDate = (TextBox)FormView1.Row.FindControl("dataStockOutDate");
            // ServiceFacade.SettingsHelper.EAPrefix = "-01-";
            string Perfix = "E" + ServiceFacade.SettingsHelper.EAPrefix + DateTime.Now.ToString("yyMMdd");
            int Count = 0;

            TList<StockOut> objStockOut = DataRepository.StockOutProvider.GetPaged("StockOutID like '" + Perfix + "' + '%'", "StockOutID desc", 0, 1, out Count);
            if (Count == 0)
                tbStockOutId.Text = Perfix + "-" + "001";
            else
            {
                tbStockOutId.Text = Perfix + "-" + String.Format("{0:000}", int.Parse(objStockOut[0].StockOutId.Substring((objStockOut[0].StockOutId.Length - 3))) + 1);
            }
            tbStockOutDate.Text = DateTime.Now.ToString("dd-MMM-yyyy");
            tbStockOutDate.Enabled = false;
        }
        else
        {
            FormView1.FooterRow.FindControl("PreviewButton").Visible = true;

            string stockOutId = Request.QueryString["StockOutID"];
            StockOut stockOut = DataRepository.StockOutProvider.GetByStockOutId(stockOutId);
            if (stockOut.IsComplete)
            {
                FormView1.FooterRow.FindControl("UpdateButton").Visible = false;
                FormView1.FooterRow.FindControl("CloseAdjust").Visible = false;
            }
            else
            {
                FormView1.FooterRow.FindControl("CloseAdjust").Visible = true;
                pn_ExportAdjustDetailsAdd.Visible = true;

            }
        }
    }
    protected void cbo_DrugID_ItemsRequested(object o, Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs e)
    {

        //DataSet dsResult = DataRepository.StockProvider.GetItems(e.Text);
        string whereClause = String.Format("DrugId IN (SELECT Stock.DrugId FROM dbo.DrugDispo INNER JOIN dbo.Stock On dbo.DrugDispo.DrugId = dbo.Stock.DrugId WHERE DrugName LIKE '{0}%')", e.Text.Replace("'", "''"));
        int count;
        TList<Stock> stocks = DataRepository.StockProvider.GetPaged(whereClause, "DrugId", 0, 10, out count);
        DataRepository.StockProvider.DeepLoad(stocks);
        stocks.Sort((s1, s2) => String.CompareOrdinal(s1.DrugIdSource.DrugName, s2.DrugIdSource.DrugName));
        foreach (Stock stock in stocks)
        {
            RadComboBoxItem item = new RadComboBoxItem();

            item.Text = stock.DrugIdSource.DrugName;
            item.Value = stock.StockId.ToString();
            item.Attributes.Add("DrugId", stock.DrugId);
            item.Attributes.Add("ExpDate", stock.ExpDate.HasValue ? stock.ExpDate.Value.ToString("MMM-yy") : "");
            item.Attributes.Add("Batch-Lot", stock.BatchLot);
            item.Attributes.Add("Quantity", stock.Quantity.ToString());
            cbo_DrugID.Items.Add(item);
            item.DataBind();
        }
    }


    private bool checkStockId(string stockId)
    {
        long Id = 0;
        bool result = long.TryParse(stockId, out Id);
        if (result)
        {
            Stock objStock = DataRepository.StockProvider.GetByStockId(long.Parse(stockId));
            if (objStock != null)
                return true;
        }
        return false;

    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (btnSave.Text == "Add")
        {
            if (checkStockId(cbo_DrugID.SelectedValue))
            {
                DateTime? expDate; DateTime dt;
                expDate = DateTime.TryParse(txtExpDate.Value, out dt) ? dt : (DateTime?)null;
                string batchLot = null;
                batchLot = (TxtBatchLot.Value == "null" || TxtBatchLot.Value.Trim() == "") ? null : TxtBatchLot.Value;

                TextBox tbStockOutId = (TextBox)FormView1.Row.FindControl("dataStockOutID");
                Stock objStock = DataRepository.StockProvider.GetByStockId(Convert.ToInt64(cbo_DrugID.SelectedValue));
                StockOutDetails objStockDetail = new StockOutDetails();
                objStockDetail.StockOutId = tbStockOutId.Text;
                objStockDetail.DrugId = objStock.DrugId;
                objStockDetail.UnitPrice = decimal.Parse(CostPriceResult.Value);
                objStockDetail.ExpDate = expDate;
                objStockDetail.BatchLot = batchLot;
                objStockDetail.Quantity = int.Parse(tbQuantity.Value);
                objStockDetail.Remark = tbRemark.Value;
                TransactionManager objTransactionManager = DataRepository.Provider.CreateTransaction();
                try
                {
                    objTransactionManager.BeginTransaction();
                    DataRepository.StockOutDetailsProvider.Save(objTransactionManager, objStockDetail);
                    if (objStock != null)
                    {
                        objStock.Quantity -= int.Parse(tbQuantity.Value);
                        if (objStock.Quantity == 0)
                            DataRepository.StockProvider.Delete(objTransactionManager, objStock);
                        else
                            DataRepository.StockProvider.Update(objTransactionManager, objStock);
                    }
                    objTransactionManager.Commit();
                    tbRemark.Value = "";
                    tbQuantity.Value = "1";
                    cbo_DrugID.Text = "";
                    TxtBatchLot.Value = "";
                    txtExpDate.Value = "";
                    cbo_DrugID.Focus();
                }
                catch (Exception)
                {
                    objTransactionManager.Rollback();
                    throw;
                }
            }

        }
    }
    [WebMethod]
    public static void DeleteStockOutDetail(string StockOutDetailId)
    {
        StockOutDetails objStockOutDetail = DataRepository.StockOutDetailsProvider.GetByStockOutDetailId(long.Parse(StockOutDetailId));
        Stock objStock = DataRepository.StockProvider.GetByDrugIdExpDateBatchLot(objStockOutDetail.DrugId, objStockOutDetail.ExpDate, objStockOutDetail.BatchLot);
        TransactionManager objTransactionManager = DataRepository.Provider.CreateTransaction();
        try
        {
            objTransactionManager.BeginTransaction();
            if (objStock != null)
            {
                objStock.Quantity += objStockOutDetail.Quantity;
                DataRepository.StockProvider.Update(objTransactionManager, objStock);
            }
            else
            {
                objStock =new Stock();
                objStock.DrugId = objStockOutDetail.DrugId;
                objStock.BatchLot = objStockOutDetail.BatchLot;
                objStock.ExpDate = objStockOutDetail.ExpDate;
                objStock.Quantity = objStockOutDetail.Quantity;
                DataRepository.StockProvider.Insert(objTransactionManager, objStock);
            }
            DataRepository.StockOutDetailsProvider.Delete(objTransactionManager, long.Parse(StockOutDetailId));

            objTransactionManager.Commit();
        }
        catch (Exception)
        {
            objTransactionManager.Rollback();
        }
    }

    protected void FormView1_ItemCommand(object sender, FormViewCommandEventArgs e)
    {
        if (e.CommandName == "CloseAdjust")
        {
            decimal Amount = 0;
            decimal totalAmount = 0;
            TextBox tbStockOutId = (TextBox)FormView1.Row.FindControl("dataStockOutID");

            //update stock
            TList<StockOutDetails> listStockOutDetail = DataRepository.StockOutDetailsProvider.GetByStockOutId(tbStockOutId.Text);
            foreach (StockOutDetails Itemdetail in listStockOutDetail)
            {
                // tinh amount cho StockOut_Amount
                Amount = Itemdetail.Quantity * Itemdetail.UnitPrice;
                totalAmount += Amount;
            }

            StockOut objStockOut = DataRepository.StockOutProvider.GetByStockOutId(tbStockOutId.Text);
            if (objStockOut != null)
            {
                objStockOut.IsComplete = true;
                objStockOut.TotalAmount = totalAmount;
                DataRepository.StockOutProvider.Update(objStockOut);
            }

            FormView1.FooterRow.FindControl("CloseAdjust").Visible = false;

        }
        if (e.CommandName == "Preview")
        {
            string StockOutId = Request.QueryString["StockOutId"].ToString();
            Response.Redirect("PreviewExportAdjust.aspx?StockOutId=" + StockOutId);
        }
    }
    protected void btn_Delete_Click(object sender, EventArgs e)
    {
        LinkButton btn_Delete = (LinkButton)sender;
        GridViewRow deleteRow = (GridViewRow)btn_Delete.NamingContainer;
        string StockOutDetailId = GridViewStockOutDetail.DataKeys[deleteRow.RowIndex].Value.ToString();
        DeleteStockOutDetail(StockOutDetailId);
        GridViewStockOutDetail.DataBind();
    }

    protected void GridViewStockOutDetail_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //kiem tra an nut delete
        string stockOutId = Request.QueryString["StockOutID"];
        StockOut stockOut = DataRepository.StockOutProvider.GetByStockOutId(stockOutId);
        if (stockOut != null && stockOut.IsComplete)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton btndelete = (LinkButton)e.Row.FindControl("btn_Delete");
                btndelete.Visible = false;

            }
        }
    }
}


